package at.irian.jsfatwork.dao.jpa;

import at.irian.jsfatwork.dao.ProviderDao;
import at.irian.jsfatwork.domain.Address;
import at.irian.jsfatwork.domain.Provider;

import javax.inject.Named;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Named("providerDao")
@Singleton
public class JpaProviderDao implements ProviderDao {

    @PersistenceContext
    private EntityManager em;

    public Provider createNew() {
        Provider provider = new Provider();
        Address address = new Address();
        provider.setAddress(address);
        return provider;
    }

    public void persist(Provider entity) {
        em.persist(entity);
    }

    @SuppressWarnings({"unchecked"})
    public List<Provider> findAll() {
        return em.createQuery("select p from Provider p").getResultList();
    }

    public Provider findById(long id) {
        return em.find(Provider.class, id);
    }

    public void delete(Provider entity) {
        em.remove(entity);
    }

}
